let layer = layui.layer;
let form = layui.form;
// =================传参方便复用==================
let query = {
  sex: '',
  username: '',
  mobile: '',
  page: 1,
  limit: 10
}
// ===========渲染=============
content()
function content() {
  axios.get('/ydd_user/list', { params: query }).then(({ data: { data: res } }) => {
    const { count, data } = res
    const str = data.map((item, index) => {
      const { username, mobile, id, icon, sex, birthday } = item
      const icons = icon ? icon : ''
      return `
      <tr>
              <td>${index + 1}</td>
              <td>${id}</td>
              <td>${username}</td>
              <td>${mobile}</td>
              <td> <img src="http://124.223.14.236:8060/${icons} " alt=""></td>
              <td>${sex === 0 ? '男' : '女'}</td>
              <td>${birthday ? birthday : ''}</td>
              <td>
                <button type="button" class="layui-btn layui-btn-xs btn_edit iconfont" id="edit" data-id="${id}">编辑
                </button>
                <button type="button" class="layui-btn layui-btn-danger layui-btn-xs btn_delete delete" data-id='${id}'> 删除
                </button>
              </td>
            </tr>`
    }).join('')
    $('#tbody').html(str)
    page(count)
  })
}
// ====================分页器======================
function page(count) {
  layui.use('laypage', function () {
    let laypage = layui.laypage;
    laypage.render({
      elem: 'test1' //注意，这里的 test1 是 ID，不用加 # 号
      , count //数据总数，从服务端得到
      , limit: query.limit
      , curr: query.page
      , limits: [2,10, 20, 30]
      , layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
      , jump: function (obj, first) {
        //obj包含了当前分页的所有参数，比如：
        // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        // console.log(obj.limit); //得到每页显示的条数

        query.page = obj.curr
        query.limit = obj.limit
        //首次不执行
        if (!first) {
          //do something
          content()
        }
      }
    })
  });
  ;
}

// ======================点击删除功能=======================
$('#tbody').on('click', '.delete', function () {
  const id = $(this).attr('data-id')
  axios({
    method: 'get',
    url: '/ydd_user/del',
    params: {
      id
    }
  }).then(({ data: { errno, errmsg } }) => {
    if (errno !== 0) return layer.msg(errmsg)
    if ($('.delete').length === 1) {
      jquery.page = jquery.page === 1 ? 1 : jquery.page - 1
    }
    content()
    return layer.msg('删除成功')
  })
})

// ========重置======
$('#reset').on('click', function () {
  $('#id1').val('')
  $('#id2').val('')
  query.username = ''
  query.mobile = ''
  query.sex =''
  content()
})
// ========================搜索功能======================
$('#search').on('click', function () {
  query.username = $('#id1').val()
  query.mobile = $('#id2').val()
  query.sex = $('#city').val()
  query.page = 1
  content()
})
// 刷新
$('#refresh').on('click', function () {
  query.username = ''
  query.mobile = ''
  query.sex=''
  content()
})

// ==========================编辑=========================
let editFormStr = `<form id="editForm" class="layui-form" lay-filter="editForm">
<!-- 存id -->
<div class="layui-form-item layui-hide">
  <label class="layui-form-label">分类名称Id</label>
  <div class="layui-input-block">
    <input type="text" name="id" required lay-verify="required" placeholder="请输入Id" autocomplete="off"
      class="layui-input" '>
  </div>
</div>

<!-- 第一行  -->
<div class="layui-form-item" style="display: flex;margin:20px 20px ">
<label >用户</label>
<div >
  <input type="text" name="username" required lay-verify="required" placeholder="" autocomplete="off"
    class="layui-input" style="width: 280px">
</div>

<label>手机号</label>
<div >
  <input type="text" name="mobile"  placeholder="" 
    class="layui-input" style="width: 280px;margin-right:40px">
</div>
</div>

<!-- 第二行-->


<div class="layui-form-item" style="display: flex;margin:20px 20px  ">
<label >密码</label>
<div >
  <input type="text" name="password"  placeholder="" autocomplete="off"
    class="layui-input" style="width: 280px">
</div>
<label  style="position: absolute;left:328px;top:74px">性别:</label>
<div style="position: absolute;left:363px;top:73px">
<input type="checkbox" name="sex" lay-skin="switch" lay-text="女|男">
</div>
</div>

<!-- 第三行-->
<div class="layui-form-item" style="display: flex;margin:20px 20px ">
<label >头像</label>
<div >
 
<div style="position: absolute;left:-58px;top:114px">
        <label class="layui-form-label"></label></label></label>
        <div class="layui-input-block">
        <button type="button" class="layui-btn layui-btn-normal" id='uploading'>点击上传</button>
        </div>
        <input class="layui-hide" type="file" id="fileCover" accept="image/jpeg,image/png,image/gif,image/bmp" />

        
 </div>

 <div  style="width:100px;height: 60px ; position: absolute;left:53px;top:154px">
    <img src="" alt="" id="img" style="width:100px;height: 60px ;">
  </div>

  <!-- <--第四行 --> 
 <div class="layui-form-item" style="position: absolute;left:430px;top:170px" >
 <div class="layui-input-block">
   <button class="layui-btn" lay-submit lay-filter="formDemo">确认</button>
   <button class="layui-btn layui-btn-primary" lay-submit lay-filter="formDemo" id='id9'>取消</button>
 </div>
</div>
</form>
`

$('body').on('click', '#uploading', function () {
  $('#fileCover').click()
})
let indexedit
$('body').on('click', '#edit', function () {
  indexedit = layer.open({
    content: editFormStr,
    title: '新增',
    type: 1,
    area: ['700px', '300px']
  });
  form.render(); // 渲染全部
  const id = $(this).attr('data-id')
  // console.log(id);
  axios.get(`/ydd_user/rowInfo?id=${id}`,).then(({ data: { data } }) => {
    // console.log(data);
    const { icon } = data
    const icons = icon ? icon : ''
    // console.log(icons);
    $('#img').prop('src', `http://124.223.14.236:8060/${icons}`)
    //给表单赋值
    form.val("editForm", data)

  })
})
// 处理图片
let newsrcs
$('body').on('change', '#fileCover', function () {
  const fdd = new FormData()
  let filescr = this.files[0]
  // console.log(filescr);
  fdd.append('file', filescr)
  if (!filescr) return
  axios.post('/common/upload?type=images', fdd).then(({ data: { data } }) => {
    newsrc = data.savePath
    newsrcs = newsrc ? newsrc : ''
    $('#img').prop('src', `http://124.223.14.236:8060/${newsrcs}`)
    console.log(data);
  })
})

// 提交图片
$('body').on('submit', '#editForm', function (e) {
  e.preventDefault()
  const fd = new FormData(this)
  fd.append('icon', newsrcs)
  axios.post('/ydd_user/update', fd).then(({ data }) => {
    content()
    layer.close(indexedit)
  })
  // fd.forEach((name, value) => {
  //   console.log(name, value);
  // })
})
// =======================新增===============
let addFormStr = `<form id="addForm" class="layui-form" >

<!-- 第一行  -->
<div class="layui-form-item" style="display: flex;margin:20px 20px ">
<label >用户</label>
<div >
  <input type="text" name="username" required lay-verify="required" placeholder="" autocomplete="off"
    class="layui-input" style="width: 280px">
</div>

<label>手机号</label>
<div >
  <input type="text" name="mobile"  placeholder="" 
    class="layui-input" style="width: 280px;margin-right:40px">
</div>
</div>

<!-- 第二行-->


<div class="layui-form-item" style="display: flex;margin:20px 20px  ">
<label >密码</label>
<div >
  <input type="text" name="password"  placeholder="" autocomplete="off"
    class="layui-input" style="width: 280px">
</div>
<label  style="position: absolute;left:328px;top:74px">性别:</label>
<div style="position: absolute;left:363px;top:73px">
<input type="checkbox" name="sex" lay-skin="switch" lay-text="女|男">
</div>
</div>

<!-- 第三行-->
<div class="layui-form-item" style="display: flex;margin:20px 20px ">
<label >头像</label>
<div >
 
<div style="position: absolute;left:-58px;top:114px">
        <label class="layui-form-label"></label></label></label>
        <div class="layui-input-block">
        <button type="button" class="layui-btn layui-btn-normal" id='uploadings'>点击上传</button>
        </div>
        <input class="layui-hide" type="file" id="fileCovers" accept="image/jpeg,image/png,image/gif,image/bmp" />

        
 </div>

 <div  style="width:100px;height: 60px ; position: absolute;left:53px;top:154px; display:none " class="box">
    <img src="" alt="" id="imgs" style="width:100px;height: 60px ;">
  </div>

  <!-- <--第四行 --> 
 <div class="layui-form-item" style="position: absolute;left:430px;top:170px" >
 <div class="layui-input-block">
   <button class="layui-btn" lay-submit lay-filter="formDemo">确认</button>
   <button class="layui-btn layui-btn-primary" lay-submit lay-filter="formDemo"  id='id8'>取消</button>
 </div>
</div>
</form>
`
let indexadd
$('#add').on('click', function () {
  indexadd = layer.open({
    content: addFormStr,
    title: '新增',
    type: 1,
    area: ['700px', '300px']
  });
  form.render(); // 渲染全部
})

$('body').on('click', '#uploadings', function () {
  $('#fileCovers').click()
})



let newsrcss
$('body').on('change', '#fileCovers', function () {
  const fdd = new FormData()
  let filescr = this.files[0]
  fdd.append('file', filescr)
  if (!filescr) return
  axios.post('/common/upload?type=images', fdd).then(({ data: { data } }) => {
    const  newsrc = data.savePath
    newsrcss = newsrc ? newsrc : ''
    $('#imgs').prop('src', `http://124.223.14.236:8060/${newsrcss}`)
    $('.box').show()
    
  })
})

// 提交图片
$('body').on('submit', '#addForm', function (e) {
  e.preventDefault()
  const fd = new FormData(this)
  fd.append('icon', newsrcss)
  axios.post('/ydd_user/add', fd).then(({ data }) => {
    content()
    layer.close(indexadd)
  })
  fd.forEach((name, value) => {
    console.log(name, value);
  })
})
$('body').on('click','#id8',function(){
  layer.close(indexadd)
})
$('body').on('click','#id9',function(){
  layer.close(indexedit)
})